
let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');
let multer = require('../../components/multerUtil');

/**
 * 查询上传文件数据 2018-10-15
 *
 * 按条件查询上传文件数据
 *
 */
router.get('/:code/basefiles/:archivesId/basefiles', filter.authorize, function (req, res, next) {
    let params = req.query;
    let code = req.params.code;
    let archivesId = req.params.archivesId;
    var limits = "";
    var sql = "";
    var datas = [];

    let tableName = "s_" + code + "_file";

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "附件所属机构编码不正确！"});
        return;
    }

    let isDelete = 0;
    if (params.isDelete !== undefined && params.isDelete !== "") {
        isDelete = 1;
    }

    sql = " where isDelete = ?";
    datas.push(isDelete);

    if (archivesId === undefined || archivesId === "") {
        res.json({"success": false, "message": "附件所属档案编码不正确！"});
        return;
    }

    sql += " and archivesId = ?";
    datas.push(archivesId);

    if (params.title !== undefined && params.title !== "") {
        sql += " and title like ?";
        datas.push("%" + params.title + "%");
    }

    req.app.db.query("select count(1) as totalCount from " + tableName + " " + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from " + tableName + " " + sql + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }
            
            res.json({"success": true, "data": results, "totalCount": totalCount, "message": ""});
        });
    });
});

/**
 * 查看上传文件数据 2018-10-15
 *
 * 按id查看指定的上传文件信息
 *
 */
router.get('/:code/basefiles/:archivesId/basefiles/:id', filter.authorize, function (req, res, next) {
    let params = req.params;
    let code = req.params.code;
    let archivesId = req.params.archivesId;

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "附件所属机构编码不正确！"});
        return;
    }

    if (archivesId === undefined || archivesId === "") {
        res.json({"success": false, "message": "附件所属档案编码不正确！"});
        return;
    }

    let tableName = "s_" + code + "_file";

    req.app.db.query("select * from " + tableName + " where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

router.get('/:code/basefiles/:archivesId/basefiles/:id/download', filter.authorize, function (req, res, next) {
    let params = req.params;
    let code = req.params.code;
    let archivesId = req.params.archivesId;

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "附件所属机构编码不正确！"});
        return;
    }

    if (archivesId === undefined || archivesId === "") {
        res.json({"success": false, "message": "附件所属档案编码不正确！"});
        return;
    }

    let tableName = "s_" + code + "_file";

    req.app.db.query("select * from " + tableName + " where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }
        let file = results[0];
        let fileName = file.title + getExtension(file.path);
        res.download(global.dirname + global.upload.path + "/" + file.code + "/" + file.path, fileName);
    });
});

function getExtension(file){
    return file.substring(file.lastIndexOf("."), file.length);
}

/**
 * 修改上传文件数据 2018-10-15
 *
 *
 */
router.put('/:code/basefiles/:archivesId/basefiles/:id', filter.authorize, multer.single("uploadFile"), function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let now = new Date();
    let code = req.params.code;
    let archivesId = req.params.archivesId;

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "附件所属机构编码不正确！"});
        return;
    }

    if (archivesId === undefined || archivesId === "") {
        res.json({"success": false, "message": "附件所属档案编码不正确！"});
        return;
    }

    let tableName = "s_" + code + "_file";
    
    if (params.id === undefined || params.id === '') {
        res.json({"success": false, "message": "上传文件编码错误！"});
        return;
    }
    
    if (params.title === undefined || params.title === '' ) {
        res.json({"success": false, "message": "上传文件标题不能为空！"});
        return;
    }
    
    req.app.db.query("update " + tableName + " set title = ?, content = ?, userId = ?, userName = ?, updateDate = ? where id = ?", [params.title, params.content, user.id, user.trueName, now, params.id], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.putMsg});
    });
});

/**
 * 新增上传文件数据 2018-10-15
 *
 *
 */
router.post('/:code/basefiles/:archivesId/basefiles', filter.authorize, multer.single("uploadFile"), function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let now = new Date();
    let code = req.params.code;
    let archivesId = req.params.archivesId;

    if (archivesId === undefined || archivesId === "") {
        res.json({"success": false, "message": "附件所属档案编码不正确！"});
        return;
    }

    let tableName = "s_" + code + "_file";

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "上传文件所属机构编码不正确！"});
        return;
    }

    if (params.title === undefined || params.title === '' ) {
        res.json({"success": false, "message": "上传文件标题不能为空！"});
        return;
    }

    if (req.file === undefined) {
        res.json({"success": false, "message": "请上传文件！"});
        return;
    }
    let path = req.file.filename;
    let fileSize = req.file.size;

    req.app.db.query("insert into " + tableName + "(code, archivesId, fileType, fileNo, title, content, path, fileSize, userId, userName, createDate, updateDate) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        [code, archivesId, 3, 1, params.title, params.content, path, fileSize, user.id, user.trueName, now, now], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.postMsg});
    });
});
    
/**
 * 删除上传文件信息 2018-10-15
 *
 * 按id删除指定的上传文件信息
 */
router.delete('/:code/basefiles/:archivesId/basefiles/:id', filter.authorize, function (req, res, next) {
    let params = req.params;
    let code = req.params.code;
    let archivesId = req.params.archivesId;

    if (code === undefined || code === "") {
        res.json({"success": false, "message": "附件所属机构编码不正确！"});
        return;
    }

    if (archivesId === undefined || archivesId === "") {
        res.json({"success": false, "message": "附件所属档案编码不正确！"});
        return;
    }

    let tableName = "s_" + code + "_file";

    if (params.id === undefined || params.id === "" || !(params.id > 0)) {
        res.json({"success": false, "message": "上传文件编码不正确！"});
        return;
    }

    req.app.db.query("update " + tableName + " set isDelete = 1 where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.deleteMsg});
    });
});
    
module.exports = router;
    